// app/controller/files.js
const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');

class FilesController extends Controller {
  async list() {
    const { ctx } = this;
    // 设置路径指向项目的 public/uploads 目录
    const uploadPath = path.join(this.config.baseDir, 'app/public/uploads');

    try {
      // 读取目录中的所有文件
      const files = fs.readdirSync(uploadPath).map(file => {
        return {
          name: file,
          url: `/public/uploads/${file}`
        };
      });

      ctx.body = {
        success: true,
        files: files
      };
    } catch (error) {
      // 捕获可能的错误，如目录不存在
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: 'Failed to read directory: ' + error.message
      };
    }
  }
}

module.exports = FilesController;
